;(function(){
    /**
     * jqGrid
     */
    $.fn.extend({
        /**
         * 初始化grid列表
         * @param options
         */
        gridView: function (options) {
            //设置父元素宽度，以控制jggrid的宽度
            $(this).css("width","95%");
            
            var ids = getIds(this);
            if(ids.length !=2)alert("jqGrid style error --> table、div");
            var tId = ids[0];//table id  列表
            var dId = ids[1];//div id 分页条
            //默认选项
            var defaultOptions = {
                url: "",
                mtype: "GET",
                styleUI: 'Bootstrap',
                datatype: 'json',//
                colModel: [],
                height: '100%',
                // width: 1650,
				autowidth:true,
                rowNum:5,
                rowList:[],
                shrinkToFit: true, //自动调整列宽
                altRows: true,
                loadtext:"加载中...",
                pager: "#" + dId,
                pagerpos:"right",
                emptyrecords:"没有相关数据",
                pgtext:"{0}/{1}",
                rownumbers:true,
                loadonce:true,
                prmNames:{rows:"showCount",page:"currentPage"},//催收系统 需要翻页参数
                loadComplete:function(){
                    $("#first_" + dId + " span.glyphicon").removeClass().addClass("btn btn-primary").html("首页");
                    $("#prev_" + dId + " span.glyphicon").removeClass().addClass("btn btn-primary").html("上一页");
                    $("#next_" + dId + " span.glyphicon").removeClass().addClass("btn btn-primary").html("下一页");
                    $("#last_" + dId + " span.glyphicon").removeClass().addClass("btn btn-primary").html("尾页");
                    $("#" + dId + "_right table").css({"margin-left":-210});
                    $(".ui-jqgrid-bdiv").css({ "overflow" : "hidden" });
                    //列内容多出 省略号表示
                    $("td[role='gridcell']").css({"textOverflow":"ellipsis"});
                    //针对详情页 催收记录 换行
                    if(tId == "cr"){
						$("#cr td[role='gridcell']").css({"textOverflow":"ellipsis","white-space":"normal",
							"word-break":"break-all", "word-wrap":"break-word","vertical-align":"middle","padding-left":"6px"});
					}
					$(tId + " .ui-jqgrid-htable").css({"background-color": "#43a0ff"});
                },
                onCellSelect:function(rowid,iCol,cellcontent,e	){
                },
				beforeRequest:function(){
					$(".ui-jqgrid-htable").css({"background-color": "#43a0ff"});
                },
				loadError:function (xhr,status,error) {
					errorPage(tId,xhr);
				}
            };
            options = $.extend(defaultOptions, options);
            $("#" + tId).jqGrid(options);
        },
        /**
         * 刷新grid列表
         */
        refreshGridView:function(){
            var ids = getIds(this,"table");
            var tId = ids[0];//table id  列表
            $("#" + tId).setGridParam({datatype:'json', page:1}).trigger('reloadGrid');
        },
		/**
		 * 刷新grid列表
		 */
		refreshGridList:function(options){
			var ids = getIds(this,"table");
			var tId = ids[0];//table id  列表
			$("#" + tId).setGridParam({datatype:'json', page:1,postData:options}).trigger('reloadGrid');
		},
		/**
         * 设置gird高度
		 * @param height
		 */
		setGridHeight:function (height) {
			var ids = getIds(this,"table");
			var tId = ids[0];//table id  列表
			$("#" + tId).setGridHeight(height);
		},
		getSelectRow:function(){
			var ids = getIds(this,"table");
			var tId = ids[0];//table id  列表
			var tableObj = $("#" +  tId);
			var ids,currentPageData = [];
			ids = tableObj.jqGrid('getGridParam', 'selarrrow');
			$.each(ids,function(i,n){
				currentPageData.push(tableObj.jqGrid('getRowData',n));
			});
			return {
				getSelectRowId:function(){
					return ids;
				},
				getSelecRowtData:function(){
					return currentPageData;
				}
				};
		},
		gridList:function(options){
			//设置父元素宽度，以控制jggrid的宽度
			$(this).css("width","99%");
			
			var ids = getIds(this);
			if(ids.length !=2)alert("jqGrid style error --> table、div");
			var tId = ids[0];//table id  列表
			var dId = ids[1];//div id 分页条
			//默认选项
			var defaultOptions = {
				url: "",
				mtype: "post",
				styleUI: 'Bootstrap',
				datatype: 'json',
			    subGrid:false,
				colModel: [],
				multiselect: true, //是否支持多选
				height: '395',
				// width: 1650,
				autowidth:true,
				rowNum:10,
				rowList:[10,50,100,200,300],
				shrinkToFit: true, //自动调整列宽
				altRows: true,
				scrollOffset:1,
				viewrecords:true,
				rownumbers:true,
				rownumWidth:75,
				recordpos:"left",
				loadtext:"加载中.....",
				pager: "#" + dId,
				pagerpos:"right",
				emptyrecords:"<i class='layui-icon' style='color: red;'>&#xe69c;</i>没有相关数据",
				pgtext:"{0}/{1}",
				recordtext:"序号{0}至序号{1} - 共{2}条",
				prmNames:{rows:"showCount",page:"currentPage"},//催收系统 需要翻页参数
				loadComplete:function(){
					var total = $("#" + tId).jqGrid('getGridParam','records');
					$("#first_" + dId + " span.glyphicon").removeClass()
                        .addClass("layui-btn layui-btn-normal").html("首页");
					$("#prev_" + dId + " span.glyphicon").removeClass()
                        .addClass("layui-btn layui-btn-normal").html("上一页");
					$("#next_" + dId + " span.glyphicon").removeClass()
                        .addClass("layui-btn layui-btn-normal").html("下一页");
					$("#last_" + dId + " span.glyphicon").removeClass()
                        .addClass("layui-btn layui-btn-normal").html("尾页");
					$("#" + dId + "_right").width(560).children().find("table").css({"margin-left":"-180px"})
						.find("#input_" + dId +" span").css({"margin-right":"25px"});
					$("#" + dId + "_center").css("textAlign","right")
                        .html("<label class='layui-btn layui-btn-normal'>共" + total + "条</label>");
					$(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
					//列内容多出 省略号表示
					$("td[role='gridcell']").css({"textOverflow":"ellipsis"});
					$("gview_"+tId+" .ui-jqgrid-htable").css({"background-color": "#E5E5E5"});
					$(".ui-th-div").height(23);
					$(".ui-paging-info").attr("id","getSUM");
					if($("#scroll").size()==0){
						var scroll = [
							'<script id="scroll" type="text/javascript" ' +
							'src="static/js/scroll/jquery.mCustomScrollbar.concat.min.js"></script>',
							'<link rel="stylesheet" href="static/js/scroll/jquery.mCustomScrollbar.css" media="all">',
							'<script type="text/javascript" src="static/call/callCommon.js?abc='+Math.random()+'"></script>'
						];
						$("body").after(scroll.join(""));
						$(".ui-jqgrid-bdiv").mCustomScrollbar({
							theme:"dark-2",
							mouseWheel:true,
							advanced:{
								updateOnContentResize:true
							}
						});
					}
				},
				loadError:function (xhr,status,error) {
					errorPage(tId,xhr);
				}
			};
			options = $.extend(defaultOptions, options);
			$("#" + tId).jqGrid(options);
        }
    });

    /**
     * 设置列
     * @param label
     * @param name
     * @param options
     * @returns {{label: *, name: *, sortable: boolean, align: string, classes: string, formatter: formatter}}
     */
    window.setColumn = function(label,name,options){
        var defaultOptions = {
			label: label,
			name: name,
            align:'left',
            classes:'',
			sortable:false,
            width:150,
            formatter:function(cellvalue, options, rowObject){
                return cellvalue;
            }
        };
        options = $.extend(defaultOptions, options);
        return options;
    };

    /**
     * 获取列表id
     * @returns {Array}
     */
    var getIds = function () {
        var ids = [];
        var arr = arguments[1] ? $(arguments[0]).children().find(arguments[1]) : $(arguments[0]).children();
        $.each(arr,function(i,v){
            var id = $(v).attr("id");
            if(id == undefined) return;
            ids.push(id);
        });
        return ids;
    };
    
    var errorPage = function(tId,xhr){
		layer.open({
			title: tId + "-错误信息",
			fixed: false,
			type: 1,
			closeBtn:0,
			content: xhr.responseText,
			area: ['800px', '450px'],
			zIndex: layer.zIndex, //重点1
			success: function(layero){
				layer.setTop(layero); //重点2
			}
		});
	}

})();